package database

import (
	"context"
	"fmt"
	"github.com/go-redis/redis/v8"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"log"
	"net/url"
	"saleforce/sf-backend-user/config"
)

func InitDb() *gorm.DB {
	database := config.DataBaseConf
	userName := database.User
	password := database.Password
	host := database.Host
	port := database.Port
	dbName := database.Dbname
	charset := database.Charset
	tz := database.Local
	password = url.QueryEscape(password)
	tz = url.QueryEscape(tz)
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=True&loc=%s", userName, password, host, port, dbName, charset, tz)
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		log.Fatal("❌ 数据库连接异常%s\n", err)
	}
	return db
}

func InitRds() *redis.Client {
	redisConf := config.RedisConf
	addr := redisConf.Addr
	password := redisConf.Password
	port := redisConf.Port
	db := redisConf.Db
	rdb := redis.NewClient(&redis.Options{
		Addr:     addr + ":" + port,
		Password: password,
		DB:       db,
	})
	ctx := context.Background()
	_, err := rdb.Ping(ctx).Result()
	if err != nil {
		log.Fatal("❌ Redis连接异常%s\n", err)
	}
	return rdb
}
